package 笔试记录.M9day7去哪儿;

import java.util.Deque;
import java.util.LinkedList;

public class Main {
    public int[] maxSlidingWindow (int[] nums, int k) {
        // write code here
        if(nums.length == 0) return nums;
        //创建单调队列用来筛选
        Deque<Integer> deque = new LinkedList<>();
        int[] arr = new int[nums.length - k + 1];//存放最大值
        int index = 0;//arr数组的下标
        //这里先对第一个窗口用队列进行处理
        for(int i = 0;i < k;i++){
            while(!deque.isEmpty() && nums[i] > deque.peekLast()) deque.removeLast();
            deque.addLast(nums[i]);
        }
        arr[index++] = deque.peekFirst();
        //窗口开始滑动
        for (int i = k; i < nums.length; i++) {
            if(deque.peekFirst() == nums[i - k]) {
                deque.removeFirst();
            }
            while(!deque.isEmpty() && nums[i] > deque.peekLast()) {
                deque.removeLast();
            }
            deque.addLast(nums[i]);
            arr[index++] = deque.peekFirst();
        }
        return arr;
    }
}
